package com.example.demo.utils;


import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.net.URL;

@Service
public class FileUploadUtil {

  private static final int BUFFER_SIZE = 2 * 1024;


  @Autowired
  private AppDataUtil appDataUtil;

  private static final Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);

  public String uploadFile(MultipartFile file) {
    String filePath = appDataUtil.getFileUploadUrl();
    if (file.isEmpty()) {
      return "文件为空";
    }
    // 获取文件名
    String fileName = file.getOriginalFilename();
    logger.info("上传的文件名为：" + fileName);
    // 获取文件的后缀名
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    logger.info("上传的后缀名为：" + suffixName);
    // 文件上传后的路径

    // 解决中文问题，liunx下中文路径，图片显示问题
    fileName = UUID.randomUUID() + suffixName;
    logger.info("上传的uuid文件名为：" + fileName);
    File dest = new File(filePath + fileName);
    logger.info("上传的uuid文件路径为：" + filePath + fileName);
    // 检测是否存在目录
    if (!dest.getParentFile().exists()) {
      dest.getParentFile().mkdirs();
    }
    try {
      file.transferTo(dest);
      return fileName;
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "上传失败";
  }


  public String downloadFile(HttpServletResponse response, String fileName) {

    if (fileName != null) {
      String realPath = appDataUtil.getFileUploadUrl();
      File file = new File(realPath, fileName);
      if (file.exists()) {
        response.addHeader("Content-Disposition",
                "inline;fileName=" + fileName);// 设置文件名
//        response.setHeader("contentType", "text/pdf/html; charset=utf-8");
//        response.setHeader("content-type", "text/pdf/html/PDF; charset=utf-8");
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
          fis = new FileInputStream(file);
          bis = new BufferedInputStream(fis);
          OutputStream os = response.getOutputStream();
          int i = bis.read(buffer);
          while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
          }
          System.out.println("success");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (bis != null) {
            try {
              bis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (fis != null) {
            try {
              fis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
    return null;
  }

  public String downloadFiles(HttpServletResponse response, String fileName) {

    if (fileName != null) {
      String realPath = appDataUtil.getFileUploadUrl();
      File file = new File(realPath, fileName);
      if (file.exists()) {
        response.addHeader("Content-Disposition",
                "inline;fileName=" + fileName);// 设置文件名
        response.setHeader("Content-Type", "application/pdf; charset=utf-8");
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
          fis = new FileInputStream(file);
          bis = new BufferedInputStream(fis);
          OutputStream os = response.getOutputStream();
          int i = bis.read(buffer);
          while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
          }
          System.out.println("success");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (bis != null) {
            try {
              bis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (fis != null) {
            try {
              fis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
    return null;
  }

  public String downloadPdfFile(HttpServletResponse response, String fileName) {

    if (fileName != null) {
      String realPath = appDataUtil.getFileUploadUrlPdf();
      File file = new File(realPath, fileName);
      if (file.exists()) {
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffixName;

        response.addHeader("Content-Disposition",
                "inline;fileName=" + fileName);// 设置文件名
        response.setHeader("contentType", "text/html; charset=utf-8");

        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
          fis = new FileInputStream(file);
          bis = new BufferedInputStream(fis);
          OutputStream os = response.getOutputStream();
          int i = bis.read(buffer);
          while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
          }
          System.out.println("success");
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (bis != null) {
            try {
              bis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (fis != null) {
            try {
              fis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
      return fileName;
    }
    return null;
  }

  public static boolean createDir(String destDirName) {// 创建目录
    File dir = new File(destDirName);
    if (dir.exists()) { // 判断目录是否存在
      System.out.println("创建目录失败，目标目录已存在！");
      return false;
    }
    if (!destDirName.endsWith(File.separator)) { // 结尾是否以"/"结束
      destDirName = destDirName + File.separator;
    }
    if (dir.mkdirs()) { // 创建目标目录
      System.out.println("创建目录成功！" + destDirName);
      return true;
    } else {
      System.out.println("创建目录失败！");
      return false;
    }
  }

  public static List splitUrl(String dataUrl) {// 分割url
    String[] dataUrlArr = dataUrl.split(",");
    List list = new ArrayList<>();
    for (int i = 0; i < dataUrlArr.length; i++) {
      list.add(dataUrlArr[i]);
    }
    return list;
  }


  public static String getFileFormat(String dataUrl) {//获取文件格式
    String[] dataUrlArr = dataUrl.split("\\.");
    String fileTypeStr = dataUrlArr[1];
    fileTypeStr = fileTypeStr.replaceAll(",","");
    fileTypeStr = fileTypeStr.toUpperCase();
    return fileTypeStr;
  }
  public static String getFileUUID(String dataUrl) {//获取文件格式
    String[] dataUrlArr = dataUrl.split("\\.");
    String fileTypeStr = dataUrlArr[0];
    fileTypeStr = fileTypeStr.replaceAll(",","");
    fileTypeStr = fileTypeStr.toUpperCase();
    return fileTypeStr;
  }


  public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)

          throws RuntimeException{

    long start = System.currentTimeMillis();

    ZipOutputStream zos = null ;
    try {

      zos = new ZipOutputStream(out);

      File sourceFile = new File(srcDir);

      compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);

      long end = System.currentTimeMillis();

      System.out.println("压缩完成，耗时：" + (end - start) +" ms");

    } catch (Exception e) {

      throw new RuntimeException("zip error from ZipUtils",e);

    }finally{

      if(zos != null){

        try {

          zos.close();

        } catch (IOException e) {

          e.printStackTrace();

        }

      }

    }



  }


  private static void compress(File sourceFile, ZipOutputStream zos, String name,
                               boolean KeepDirStructure) throws Exception{

    byte[] buf = new byte[BUFFER_SIZE];
    if(sourceFile.isFile()){
      // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
      zos.putNextEntry(new ZipEntry(name));
      // copy文件到zip输出流中
      int len;
      FileInputStream in = new FileInputStream(sourceFile);
      while ((len = in.read(buf)) != -1){
        zos.write(buf, 0, len);
      }
      // Complete the entry
      zos.closeEntry();
      in.close();
    } else {
      File[] listFiles = sourceFile.listFiles();
      if(listFiles == null || listFiles.length == 0){
        // 需要保留原来的文件结构时,需要对空文件夹进行处理
        if(KeepDirStructure){
          // 空文件夹的处理
          zos.putNextEntry(new ZipEntry(name + "/"));
          // 没有文件，不需要文件的copy
          zos.closeEntry();
        }

      }else {
        for (File file : listFiles) {
          // 判断是否需要保留原来的文件结构
          if (KeepDirStructure) {
            // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
            // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
            compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
          } else {
            compress(file, zos, file.getName(),KeepDirStructure);
          }
        }
      }
    }
  }

  public static void deleteDir(String dirPath)
  {
    File file = new File(dirPath);
    if(file.isFile())
    {
      file.delete();
    }else
    {
      File[] files = file.listFiles();
      if(files == null)
      {
        file.delete();
      }else
      {
        for (int i = 0; i < files.length; i++)
        {
          deleteDir(files[i].getAbsolutePath());
        }
        file.delete();
      }
    }
  }


  public static void main(String[] args) {

//    String res = downloadFromUrl("https://image.jpg","E:/");
    String res = downloadFromUrl("http://183.194.254.24:8087/lsj/file/downloadPdf?fileName=李鑫泉粮食收购许可证.pdf","E:/lsjDownload/");
    System.out.println(res);
  }


  public static String downloadFromUrl(String url,String dir) {

    try {
      URL httpurl = new URL(url);
      String fileName = getFileNameFromUrl(url);
      System.out.println(fileName);
      File f = new File(dir + fileName);
      FileUtils.copyURLToFile(httpurl, f);
    } catch (Exception e) {
      e.printStackTrace();
      return "Fault!";
    }
    return "Successful!";
  }

  public static String getFileNameFromUrl(String url){
    String name = url.split("=")[1];
//    String name = "112233.pdf";
    return name;
  }




}
